package meta

import (
	"github.com/micro-plat/lib4go/db"
	"github.com/micro-plat/lib4go/types"
)

// ColumnDef 定义了列的属性
type ColumnDef struct {
	OldName         string `json:"old_name"`
	Name            string `json:"name"`
	Type            string `json:"type"`
	IsNullable      bool   `json:"is_nullable"`
	DefaultValue    string `json:"default_value"`
	IsAutoIncrement bool   `json:"is_auto_increment"`
	IsPK            bool   `json:"is_pk"`
	Comment         string `json:"title"`
}

func apply(db db.IDBExecuter, table types.IXMap) error {
	tableName := table.GetString("name")
	columns := make([]ColumnDef, 0)

	colums := table.GetArray("columns")
	for _, xcol := range colums {
		col := xcol.(types.XMap)
		columns = append(columns, ColumnDef{
			Name:            col.GetString("name"),
			Type:            col.GetString("type"),
			IsNullable:      col.GetBool("is_nullable"),
			DefaultValue:    col.GetString("default_value"),
			IsAutoIncrement: col.GetBool("is_auto_increment"),
			IsPK:            col.GetBool("is_pk"),
			Comment:         col.GetString("title"),
			OldName:         col.GetString("old_name", col.GetString("name")),
		})
	}
	return appSchema(db, tableName, columns)
}
